package com.dl7.mvp.module.video.player;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PointF;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.bumptech.glide.Glide;
import com.danikula.videocache.HttpProxyCacheServer;
import com.dl7.mvp.XApp;
import com.dl7.mvp.R;
import com.dl7.mvp.adapter.SlideInBottomAdapter;
import com.dl7.mvp.injector.components.DaggerVideoPlayerComponent;
import com.dl7.mvp.injector.modules.VideoPlayerModule;
import com.dl7.mvp.local.table.VideoInfo;
import com.dl7.mvp.module.base.BaseActivity;
import com.dl7.mvp.module.base.IBasePresenter;
import com.dl7.mvp.module.base.ILoadDataView;
import com.dl7.mvp.utils.CommonConstant;
import com.dl7.mvp.utils.PreferencesUtils;
import com.dl7.player.media.IjkPlayerView;
import com.dl7.recycler.adapter.BaseQuickAdapter;
import com.dl7.recycler.helper.RecyclerViewHelper;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import tv.danmaku.ijk.media.player.IMediaPlayer;

import static com.dl7.mvp.utils.CommonConstant.VIDEO_DATA_KEY;

public class VideoPlayerActivity extends BaseActivity<IBasePresenter> implements ILoadDataView<List<VideoInfo>> {
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.video_player)
    IjkPlayerView mPlayerView;

    @BindView(R.id.related_video_list)
    RecyclerView mRvVideoList;
    @Inject
    BaseQuickAdapter mAdapter;

    private VideoInfo mVideoData;

    public static void launch(Context context, VideoInfo data) {
        Intent intent = new Intent(context, VideoPlayerActivity.class);
        intent.putExtra(VIDEO_DATA_KEY, data);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(R.anim.slide_bottom_entry, R.anim.hold);
    }

    public static void launchForResult(Fragment fragment, VideoInfo data) {
        Intent intent = new Intent(fragment.getContext(), VideoPlayerActivity.class);
        intent.putExtra(VIDEO_DATA_KEY, data);
        fragment.startActivityForResult(intent, CommonConstant.VIDEO_REQUEST_CODE);
        fragment.getActivity().overridePendingTransition(R.anim.slide_bottom_entry, R.anim.hold);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_video_player;
    }

    @Override
    protected void initInjector() {
        mVideoData = getIntent().getParcelableExtra(VIDEO_DATA_KEY);
        XApp.mPlayingUrl = mVideoData.getUrl();
        DaggerVideoPlayerComponent.builder()
                .applicationComponent(getAppComponent())
                .videoPlayerModule(new VideoPlayerModule(this, mVideoData.getAlbumId()))
                .build()
                .inject(this);
    }

    @Override
    protected void initViews() {
        initPlayer(true);
        SlideInBottomAdapter slideAdapter = new SlideInBottomAdapter(mAdapter);
        RecyclerViewHelper.initRecyclerViewV(this, mRvVideoList, slideAdapter);
        mRvVideoList.setLayoutManager(new SnappingLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    private void initPlayer(boolean isFirst) {
        String url = mVideoData.getUrl();
        if (PreferencesUtils.isCacheVideoAlways(this)) {
            HttpProxyCacheServer proxy = XApp.getProxy(getApplicationContext());
            url = proxy.getProxyUrl(mVideoData.getUrl());
        }

        if (isFirst) {
            mPlayerView.init();
            Glide.with(this).load(mVideoData.getImage()).fitCenter().into(mPlayerView.mPlayerThumb);
            mPlayerView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(IMediaPlayer mp) {
                    mPlayerView.start();
                }
            });
            mPlayerView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(IMediaPlayer iMediaPlayer) {
                    List<VideoInfo> videoInfos = mAdapter.getData();
                    for (int i = 0; i < videoInfos.size(); i++) {
                        if (TextUtils.equals(videoInfos.get(i).getUrl(), mVideoData.getUrl())) {
                            // 循环播放
                            int index = i + 1;
                            if (index >= videoInfos.size()) {
                                index = 0;
                            }
                            playNewVideo((VideoInfo) mAdapter.getItem(index));
                            break;
                        }
                    }
                }
            });
        }
        mPlayerView.setTitle(mVideoData.getName())
                .setVideoSource(null, url, null, null, null);
    }

    @Override
    protected void updateViews() {
        mPresenter.getData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPlayerView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPlayerView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPlayerView.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mPlayerView.configurationChanged(newConfig);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mPlayerView.handleVolumeKey(keyCode)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mPlayerView.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }

//    @OnClick(R.id.iv_video_download)
//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.iv_video_download:
//                if (view.isSelected()) {
//                    DialogHelper.checkDialog(this, mVideoData);
//                } else {
//                    DialogHelper.downloadDialog(this, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            DownloaderWrapper.start(mVideoData);
//                            mIvVideoDownload.setSelected(true);
//                            SnackbarUtils.showDownloadSnackbar(VideoPlayerActivity.this, "任务正在下载", true);
//                        }
//                    });
//                }
//                break;
//        }
//    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        intent.putExtra(CommonConstant.RESULT_KEY, mVideoData.isCollect());
        setResult(RESULT_OK, intent);
        super.finish();
        overridePendingTransition(R.anim.hold, R.anim.slide_bottom_exit);
    }

    @Override
    public void loadData(List<VideoInfo> videoList) {
        mAdapter.updateItems(videoList);
    }

    @Override
    public void loadMoreData(List<VideoInfo> videoList) {
        mAdapter.loadComplete();
        mAdapter.addItems(videoList);
    }

    @Override
    public void loadNoData() {
        mAdapter.loadAbnormal();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        VideoInfo videoInfo = intent.getParcelableExtra(VIDEO_DATA_KEY);
        playNewVideo(videoInfo);
    }

    public void playNewVideo(VideoInfo videoInfo) {
        mVideoData = videoInfo;
        mPlayerView.stop();
        initPlayer(false);

        List<VideoInfo> datas = mAdapter.getData();
        for (int i = 0; i < datas.size(); i++) {
            if (TextUtils.equals(datas.get(i).getUrl(), videoInfo.getUrl())) {
                mRvVideoList.smoothScrollToPosition(i);
                break;
            }
        }
    }

    public class SnappingLinearLayoutManager extends LinearLayoutManager {
        public SnappingLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                           int position) {
            RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
            smoothScroller.setTargetPosition(position);
            startSmoothScroll(smoothScroller);
        }

        private class TopSnappedSmoothScroller extends LinearSmoothScroller {
            public TopSnappedSmoothScroller(Context context) {
                super(context);

            }

            @Override
            public PointF computeScrollVectorForPosition(int targetPosition) {
                return SnappingLinearLayoutManager.this
                        .computeScrollVectorForPosition(targetPosition);
            }

            @Override
            protected int getVerticalSnapPreference() {
                return SNAP_TO_START;
            }
        }
    }
}
